package io.reactivex.rxjava3.harmony.schedulers;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.harmony.plugins.RxHarmonyPlugins;

public class HarmonySchedulers {

    private static final class MainHolder {
        static final Scheduler DEFAULT
                = new HandlerScheduler(new EventHandler(EventRunner.getMainEventRunner()),true);
    }

    private static final Scheduler MAIN_THREAD =
            RxHarmonyPlugins.initMainThreadScheduler(() -> MainHolder.DEFAULT);

    /**
     * A {@link Scheduler} which executes actions on the Android main thread.
     * <p>
     * The returned scheduler will post asynchronous messages to the looper by default.
     *
     * @see #from(EventRunner)
     */
    public static Scheduler mainThread() {
        return RxHarmonyPlugins.onMainThreadScheduler(MAIN_THREAD);
    }

    /**
     * A {@link Scheduler} which executes actions on {@code looper}.
     * <p>
     * The returned scheduler will post asynchronous messages to the looper by default.
     *
     * @see #from(EventRunner, boolean)
     */
    public static Scheduler from(EventRunner looper) {
        return from(looper, true);
    }

    /**
     * A {@link Scheduler} which executes actions on {@code looper}.
     * <p>
     * The returned scheduler will post asynchronous messages to the looper by default.
     */
    public static Scheduler from(EventRunner looper, boolean async) {
        if (looper == null) throw new NullPointerException("looper == null");
        async = true;
        return new HandlerScheduler(new EventHandler(looper),async);
    }

    private HarmonySchedulers() {
        throw new AssertionError("No instances.");
    }
}
